<?php
session_start();

function login() {
    $args = filter_input_array(INPUT_POST, array(
        'username' => FILTER_DEFAULT,
        'password' => FILTER_DEFAULT
    ));
    if ($args === null || $args === false || count(array_filter($args, function($arg) {
                        return $arg === false || $arg === null;
                    })) !== 0) {
        throw new Exception('args error');
    }
    if (isset($args['username']) && isset($args['password'])) {
        if ($args['username'] === "") {
            /* echo json_encode(array('result' => 1)); */
			throw new Exception('username null');
        }
        if ($args['password'] === "") {
            /* echo json_encode(array('result' => 2)); */
			throw new Exception('password null');
        }
        $connect = new CONNECT();
        $db = $connect->connecttodb();
        $action = $db->prepare("select * from admin where name = ?");
        $action->execute(array($args['username']));
        $result = $action->fetchAll();
        if (count($result) === 0) {
            throw new Exception('username error');
        }
        if (md5($args['password']) !== $result[0]['password']) {
            throw new Exception('password error');
        }
        $_SESSION["name"] = $args['username'];
        $_SESSION["status"] = true;
        if ($result[0]['root'] === '1') {
            $_SESSION['admin'] = true;
        } else {
            $_SESSION['admin'] = false;
        }
        return array();
    }
}

function addManager() {
	if($_SESSION['admin'] !== true)
	{
		throw new Exception('not login');
	}
    $args = filter_input_array(INPUT_POST, array(
        'name' => FILTER_DEFAULT,
        'password' => FILTER_DEFAULT,
        'duty' => FILTER_DEFAULT,
        'number' => FILTER_DEFAULT
    ));
    if ($args === null || $args === false || count(array_filter($args, function($arg) {
                        return $arg === false || $arg === null;
                    })) !== 0) {
        throw new Exception('参数错误！');
    }
    $connect = new CONNECT();
    $db = $connect->connecttodb();
    $action = $db->prepare("SELECT * FROM `admin` WHERE name = ?");
    $action->execute(array($args['name']));
    $admin = $action->fetchAll();
    if (count($admin)) {
        throw new Exception('管理员已存在！');
    }
    $db->prepare("INSERT INTO `admin`(`name`, `password`, `duty`, `number`, `root`) VALUES (?,?,?,?,0)")
            ->execute(array($args["name"], md5($args["password"]), $args["duty"], $args["number"]));
    return array();
}

function addBlacklist()
{
	if($_SESSION['status'] !== true)
	{
		throw new Exception('not login');
	}
    $arg = filter_input(INPUT_POST, 'name', FILTER_DEFAULT);
    if ($arg === null || $arg === false) 
    {
        throw new Exception('参数错误');
    }
    else
    {
        $connect = new CONNECT();
        $connect = $connect->connecttodb();
        $action = $connect->prepare("SELECT * FROM `blacklist` WHERE name = ?");
        $action->execute(array($arg));
        $result = $action->fetchAll();
        if (count($result)) {
            throw new Exception("该用户已在黑名单！");
        } 
        else 
        {
            $action = $connect->prepare("INSERT INTO `blacklist`(`name`) VALUES (?)");
            $result = $action->execute(array($arg));
            if ($result) {
                return array();
            }
        }
    }
}

/* function applySite() */
/* { */
/*     $args = filter_input_array(INPUT_POST, array( */
/*         'from_year' => FILTER_VALIDATE_INT, */
/*         'from_month' => FILTER_VALIDATE_INT, */
/*         'from_day' => FILTER_VALIDATE_INT, */
/*         'to_year' => FILTER_VALIDATE_INT, */
/*         'to_month' => FILTER_VALIDATE_INT, */
/*         'to_day' => FILTER_VALIDATE_INT, */
/*         'activity' => FILTER_DEFAULT, */
/*         'leader' => FILTER_DEFAULT, */
/*         'number' => FILTER_DEFAULT, */
/*         'sum_member' => FILTER_VALIDATE_INT, */
/*         'sum' => FILTER_VALIDATE_INT */
/*         )); */

/* 	if($args === null || $args === false || count(array_filter($args, function($arg) { */
/* 		return $arg === false || $arg === null; */
/* 	})) !== 0) */
/* 	{ */
/* 		throw new Exception('args error'); */
/* 	} */		
/* 	if(isset($args["activity"]) && isset($args["leader"]) && */
/* 		isset($args["number"])) { */
/* 		if($args["activity"] === "" || $args["leader"] === "" || */
/* 			$args["number"] === ""){ */
/* 			throw new Exception("请填写完整信息！"); */
/* 		}elseif($args["sum_member"] < $args["sum"]){ */
/* 			throw new Exception("您不能申请大于项目总人数的位置数！"); */
/* 		}else{ */
/* 			$start = $args["from_year"]."-".$args["from_month"]."-".$args["from_day"]; */
/* 			$end = $args["to_year"]."-".$args["to_month"]."-".$args["to_day"]; */
/* 			$now = date("Y-n-j"); */
/* 			if(!checkdate($args["from_month"], $args["from_day"], $args["from_year"]) || */ 
/* 				!checkdate($args["to_month"], $args["to_day"], $args["to_year"])){ */
/* 				throw new Exception("时间格式有误！illeagal"); */
/* 			}elseif(strtotime($start) < strtotime($now)){ */
/* 				throw new Exception("申请时间有误！"); */
/* 			}elseif(strtotime($start) > strtotime($end)){ */
/* 				throw new Exception("起始时间不能大于终止时间！"); */
/* 			}else{ */
/*                 apply_just_to_keep_neat($start, $end); */
/* 			} */
/* 		} */
/* 	} */

/* 	return array(); */
/* } */

/* function apply_just_to_keep_neat($start, $end) { */
/*     $connect = new CONNECT(); */
/*     $connect = $connect->connecttodb(); */
/*     $action = $connect->prepare("SELECT * FROM apply_site WHERE activity = ? AND leader = ? AND time_from = ? AND time_to = ?"); */
/*     $action->execute(array($_POST["activity"], $_POST["leader"], $start, $end)); */
/*     $result = $action->fetchAll(); */
/*     if (count($result)) { */
/*         throw new Exception("该项目在同一时间段重复申请！"); */
/*     } */

/*     $nameForSite = explode("，", $_POST["name"]); */
/*     if (count($nameForSite) != $_POST["sum"]) { */
/*         throw new Exception("申请的位置数和成员名单不符，或者没有使用全角标点！"); */
/*     } */

/*     $request = new REQUEST(); */
/*     $num = $request->site_rest($start, $end); */
/*     if ((12 - $num) >= $_POST["sum"]) { */
/*         $connect = new CONNECT(); */
/*         $connect = $connect->connecttodb(); */
/*         $action = $connect->prepare("SELECT * FROM `blacklist`"); */
/*         $action->execute(); */
/*         $result = $action->fetchAll(); */
/*         $sumofblacklist = count($result); */
/*         for ($j = 0; $j < $_POST["sum"]; $j++) { */
/*             for ($i = 0; $i < $sumofblacklist; $i++) { */
/*                 if ($result[0][$i] == $nameForSite[$j]) { */
/*                     throw new Exception("抱歉，第" . $j . "位成员在黑名单中"); */
/*                 } */
/*             } */
/*         } */
/*         $connect = new CONNECT(); */
/*         $connect = $connect->connecttodb(); */
/*         $action = $connect->prepare("INSERT INTO `apply_site`(`activity`, `leader`, `number`, `sum_member`, `sum`, `time_from`, `time_to`, `apply_time`, `detail`, `status`) VALUES (?,?,?,?,?,?,?,?,?,0)"); */
/*         $resultofinsert = $action->execute(array($_POST["activity"], $_POST["leader"], $_POST["number"], $_POST["sum_member"], $_POST["sum"], $start, $end, date("Y-n-j H:i:s"), $_POST["detail"])); */
/*         $action1 = $connect->prepare("SELECT `id` FROM `apply_site` WHERE activity = ? AND leader = ? AND time_from = ? AND time_to = ?"); */
/*         $action1->execute(array($_POST["activity"], $_POST["leader"], $start, $end)); */
/*         $resultofid = $action1->fetchAll(); */

/*         if (isset($_POST["others"]) && $_POST["others"] != "") { */
/*             $action1 = $connect->prepare("INSERT INTO `team_member`(`id`, `member`, `have_site`) VALUES (?,?,-1)"); */
/*             $action1->execute(array($resultofid[0][0], $_POST["others"])); */
/*         } */

/*         $action2 = $connect->prepare("INSERT INTO `team_member`(`id`, `member`, `have_site`) VALUES (?,?,1)"); */
/*         for ($i = 0; $i < $_POST["sum"]; $i++) { */
/*             $resultofinsert = $action2->execute(array($resultofid[0][0], $nameForSite[$i])); */
/*         } */

/*         if ($resultofinsert) { */
/*             throw new Exception("申请成功，等待管理员审核……"); */
/*         } else { */
/*             if (!$resultofinsert) { */
/*                 echo "\nPDO::errorInfo():\n"; */
/*                 print_r($action2->errorInfo()); */
/*             } */
/*         } */
/*     } else { */
/*         throw new Exception("很抱歉，位置不足！"); */
/*     } */
/* } */

try {
    $method = filter_input(INPUT_GET, 'method');
    if (function_exists($method)) {
		include_once __DIR__."/../model/model.php";
		$result = call_user_func($method);
		echo json_encode(array_merge(array('result' => true), $result));
    } else {
		throw new Exception('no method');
	}
} catch (Exception $exc) {
    echo json_encode(array_merge(array('result' => false), array('msg' => $exc->getMessage())));
}
